<template>
  <el-container direction="vertical">
    <div
      @click.stop="clic"
      class="cu row el-alert el-alert--info is-light"
      v-show="isphone"
    >
      <div class="col">
        <el-icon :style="{ transform: 'translateY(-1px)' }">
          <warning-filled />
        </el-icon>
        {{ title }}
      </div>
      <div @click.stop="isphone = false" :style="{ width: '40px' }">
        <el-icon>
          <Close />
        </el-icon>
      </div>
    </div>
    <HeadNav
      ref="headnav"
      :myteam="myteam"
      :icon="
        myteam.other?.saasTeamLogo
          ? myteam.other?.saasTeamLogo
          : 'https://cdn.hterobot.com/image/xinhuashudianlogo.jpg'
      "
    >
    </HeadNav>
    <router-view class="main" v-if="show" v-slot="{ Component }">
      <keep-alive :max="10" :include="['', '', 'Home']">
        <component :is="Component" />
      </keep-alive>
      <!-- <keep-alive :max="10" :include="['questionbankindex', 'questionindex', 'Home']">
                <component :is="Component" />
            </keep-alive> -->
    </router-view>
  </el-container>
</template>

<script setup lang="ts">
import { Close, WarningFilled } from "@element-plus/icons-vue";
import { useStorage, useStyleTag } from "@vueuse/core";
import { ElNotification } from "element-plus";
import { computed, onMounted, provide, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Storekey } from "../../interface";
import Studycodemodel from "../../mysql_interface/studycodemodel";
import { SET_TEAM } from "../../ojSass/store/mutation-types";
import HeadNav from "../headNav.vue";
const show = ref(false);
const store = useStore(Storekey);
const code = ref<{
  error: number;
  msg?: string;
  data?: Studycodemodel.Iuserquestioninfo[];
  run?: true;
}>();
const socket = computed(() => {
  return store.state.socket;
});

const headnav = ref();

provide("headnav", headnav);
provide("headnavdialogVisible", () => {
  headnav.value.shoudialogVisible("登录");
  return true;
});
provide("runcode", () => {
  code.value = undefined;
  return true;
});
provide("getcode", code);

const router = useRouter();
const user = computed(() => {
  return store.state.user;
});
const teamId = computed(() => {
  return user.value?.teamid;
});

const isphone = ref(false);
const title = ref("您还没有绑定手机号，无法收到通知信息，可点击绑定!");
function clic() {
  console.log(headnav.value.shoudialogVisible("修改个人信息"));
}
watch(
  () => user.value,
  (v) => {
    if (v && !v.phonenum) {
      isphone.value = true;
    }
  }
);

onMounted(async () => {
  // 先刷新登录信息后校验团队id
  await store.dispatch("actiononline");
  if (!user.value) {
    console.error("actiononline user is undefined", user.value);
    router.push({ name: "登录" });
    return;
  }
  // // 判断团队
  // await compareTeamId()
  await store.dispatch("actionarticle");
  await store.dispatch("actionlabel");
  show.value = true;
  if (socket.value) {
    store.dispatch("actiontime");
    const v = socket.value;
    v.on("runcode", (data) => {
      code.value = data;
    });
    v.on("notification", (data) => {
      const { title, context, type } = data;
      ElNotification({
        title,
        message: context,
        type,
      });
    });
  }
  // 路由权限校验
  permissions();
});

// 路由权限校验
function permissions() {
  router.beforeEach((to, from, next) => {
    try {
      // 同一页面 query不同  不走online
      if (from.name === to.name) {
        console.log("from.name:", from.name, "to.name:", to.name);
        return next();
      }
      //
      if (to.path !== "/login") {
        store.dispatch("actiononline").then((e) => {
          if (!e) {
            console.log("actiononline return", e);
            next("/login");
          }
        });
      }
      next();
    } catch (error) {
      console.error("beforeEach onlineRet error", error);
      next("/login");
    }
  });
}

const _myteam = localStorage.getItem("myTeam");
const myteam = useStorage<Studycodemodel.Iteam>(
  "my-team",
  _myteam ? JSON.parse(_myteam) : { color: "--sass-blue-color" }
);
const mystyle = useStyleTag(
  // `:root { --color-cheng: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'});
  // --color-cheng2: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'}2);
  // --color-cheng3: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'}3) }`
  `:root { 
        --color-cheng: var(--sass-color-blue);
        --color-cheng2: var(--sass-color-blue2);
        --color-cheng3: var(--sass-color-blue3) }`
);
// 监听团队切换
watch(
  () => teamId.value,
  async (o, n) => {
    if (o && o !== n) {
      console.log("index.vue actionteam", o, n);
      await store.dispatch("actionteam");
      const team = store.state.team?.rows.find((e) => e.color);
      myteam.value = {
        ID: team?.ID,
        name: team?.name,
        color: team?.color,
        other: team?.other,
      };
      // mystyle.css.value = `:root { --color-cheng: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'});--color-cheng2: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'}2);--color-cheng3: var(--color-${myteam.value.color ? myteam.value.color : '-cheng'}3) }`
      mystyle.css.value = `:root {
                 --color-cheng: var(--sass-color-blue);
                --color-cheng2: var(--sass-color-blue2);
                --color-cheng3: var(--sass-color-blue3) }`;
    } else {
      store.commit(SET_TEAM, null);
    }
  }
);

defineExpose({
  title,
  isphone,
});
</script>

<style scoped>
.router-content {
  /* 确保内容区域有正确的容器行为 */
  position: relative;
  width: 100%;
}

/* 针对 el-container 的高度设置 */
.el-container {
  height: 100vh;
}

/* 手机端 el-container 自适应高度 */
:global(.phone-device) .el-container {
  height: auto !important;
  min-height: 100vh;
}

/* 桌面端 el-container 固定高度 */
:global(.desktop-device) .el-container {
  height: 100vh;
}
</style>

<style>
</style>
